package cn.jiyun.service.impl;

import cn.jiyun.commons.MD5Util;
import cn.jiyun.commons.StringUtil;
import cn.jiyun.commons.mailutils.EmailUtil;
import cn.jiyun.commons.vo.BootstrapTableData;
import cn.jiyun.dao.domain.User;
import cn.jiyun.dao.dto.UserRole;
import cn.jiyun.dao.mapper.UserMapper;
import cn.jiyun.dao.mapper.UserRoleMapper;
import cn.jiyun.service.UserService;
import cn.jiyun.service.dto.JsonRes;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public User loginUser(User user) {
        Example example = new Example(User.class);
        example.createCriteria()
                // 设置查询条件：用户名
                .andEqualTo("password", MD5Util.getMD5(user.getPassword()))
                // 设置查询条件：密码
                .andEqualTo("username", user.getUsername());
        List<User> userList = userMapper.selectByExample(example);
        return userList.isEmpty() ? null : userList.get(0);
    }

    @Override
    public BootstrapTableData getPaginatedUsers(User userData, Integer pageNumber, Integer pageSize, String ordername, String order) {
        // 如果没有指定排序字段，则默认使用userid进行排序
        ordername = StringUtil.isNotEmpty(ordername) ? ordername : "id";
        // 如果没有指定排序方式，则默认使用倒序排序
        order = StringUtil.isNotEmpty(order) ? order : "desc";

        PageHelper.startPage(pageNumber, pageSize);

        List<UserRole> userRoles = userRoleMapper.selectByCondition(userData, ordername, order);

        PageInfo<UserRole> pageInfo = new PageInfo<>(userRoles);

        BootstrapTableData tableData = new BootstrapTableData();
        tableData.setTotal(pageInfo.getTotal());
        tableData.setRows(pageInfo.getList());

        return tableData;
    }

    @Override
    public JsonRes reserveUser(User user) {
        log.info("user:[{}]",user);
        User oldUser = existUserWithUsername(user.getUsername());
        user.setUpdateTime(new Date());
        if (user.getId() == null){
            if (oldUser != null){
                new JsonRes(1,"用户名已存在");
            }
            // 新增
            user.setUserType("1");
            user.setCreateTime(new Date());
            userMapper.insert(user);
        }else {
            // 修改
            if (oldUser!= null && !user.getId().equals(oldUser.getId()) ){
                new JsonRes(1,"用户名已存在");
            }
            userMapper.updateByPrimaryKeySelective(user);
        }
        return new JsonRes(0,"success");
    }

    @Override
    public boolean deleteUser(List<Integer> ids) {
        Example example = new Example(User.class);
        // 使用in设置删除用户的条件
        example.createCriteria().andIn("id", ids);
        userMapper.deleteByExample(example);
        return true;
    }

    public User existUserWithUsername(String username) {
        Example example = new Example(User.class);
        // 设置查询条件
        example.createCriteria().andEqualTo("username", username);
        List<User> users = userMapper.selectByExample(example);
        // 用户名不能重复，因此最多查询一条记录
        User nameUser = null;
        if (users != null && users.size() > 0) {
            nameUser = users.get(0);
        }
        // 返回根据用户名查找到的用户信息
        return nameUser;
    }

    @Override
    public JsonRes sendEmailCode(String email, String code) {
        JsonRes<String> result = new JsonRes<>();
        // 检查是否为空
        if (StringUtil.isEmpty(email)){
            result.setCode(1);
            result.setMessage("email为空");
            return result;
        }
        // 检查邮箱格式是否正确
        if (!EmailUtil.checkEmail(email)){
            result.setCode(1);
            result.setMessage("邮箱格式不正确，请检查");
            return result;
        }
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("email",email);
        List<User> users = userMapper.selectByExample(example);
        if (users.isEmpty()){
            result.setMessage("邮箱不存在");
            return result;
        }
        // 发送邮件
        boolean sendResult = EmailUtil.sendEmail(email, "会议管理系统", code);
        if (sendResult) {
            log.info("email:[{}]send code successed:[{}]", email, code);
        } else {
            log.info("email:[{}]send code failed:[{}]", email, code);
        }
        result.setCode(0);
        result.setMessage("邮件已发送，请注意查看");
        return result;
    }

    @Override
    public JsonRes resetPassword(User user, String registerCode, String sessionCode) {
        JsonRes jsonRes = new JsonRes(1);
        // 参数校验
        if (StringUtil.isEmpty(user.getEmail())){
            jsonRes.setMessage("电子邮箱为空");
            return jsonRes;
        }
        if (StringUtil.isEmpty(user.getPassword())){
            jsonRes.setMessage("密码为空");
            return jsonRes;
        }
        if (!registerCode.equals(sessionCode)){
            jsonRes.setMessage("验证码不正确");
            return jsonRes;
        }
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("email",user.getEmail());
        List<User> users = userMapper.selectByExample(example);
        if (users.isEmpty()){
            jsonRes.setMessage("邮箱不存在");
            return jsonRes;
        }
        if (users.size() > 1){
            jsonRes.setMessage("系统错误，请联系管理员");
            return jsonRes;
        }
        User oldUser = users.get(0);
        oldUser.setPassword(MD5Util.getMD5(user.getPassword()));
        oldUser.setUpdateTime(new Date());
        userMapper.updateByPrimaryKey(oldUser);
        jsonRes.setCode(0);
        jsonRes.setMessage("success");
        return jsonRes;
    }
}
